import {useCallback, useEffect, useRef, useState} from 'react';
import {
  Empty,
  ModalDir,
  ObserverButton,
  ObserverText,
  ObserverView,
  Switch,
} from '../../../components';
import {FlatList, Modal, TouchableOpacity, View} from 'react-native';
import {
  BuyChapter,
  Collect,
  postChapterInfo,
  postChapterList,
  UserAssets,
} from '../../../services';
import {observer} from 'mobx-react-lite';
import {useGlobalStore, useOtherStore, useUserInfoStore} from '../../../mobx';
import {LoadImgs} from '../FirstDetail';
import {ScrollFood, ScrollHead} from './ScrollHead';
import {dpw12, dpw16} from '../../../constants';
import {ChapterItem} from '..';
import {useFocusEffect} from '@react-navigation/native';

interface DataItem {
  ArticleId: number;
  AutoSubscribe: boolean;
  ChapterId: number;
  Content: string;
  FreeFlag: boolean;
  HasPurchase: boolean;
  ImageList: string[];
  NextChapter: DataItem;
  Points: number;
  PreviousChapter: DataItem;
  Title: string;
  VipFree: boolean;
}

const AutoPayChapter = observer(() => {
  const {theme} = useGlobalStore();

  const onAutoPay = (v: boolean) => {
    // setItem(AUTO_LOGIN, v)
    //   .then(() => {
    //     changeAutoLogin(v);
    //   })
    //   .catch(() => {});
  };

  return <Switch theme={theme} value={false} onValueChange={onAutoPay} />;
});

const ReaderDetail = ({navigation, route}: any) => {
  const {bId, chapId, type, conTitle, chapterCount, author} =
    route.params || {};
  const [data, setData] = useState<DataItem[]>([]);
  const {userInfo} = useUserInfoStore();
  const {changeToastKey} = useGlobalStore();
  const {foucs, changeFoucs} = useOtherStore();
  const [isScrollUp, setIsScrollUp] = useState(true);
  const lastScrollYRef = useRef(0);
  const [title, setTitle] = useState('');
  const [coin, setCoin] = useState(0);
  const [visible, setVisible] = useState(false);
  const [{chaplist, chapTotal, pageIndex}, setChapList] = useState<{
    chaplist: ChapterItem[];
    chapTotal: number;
    pageIndex: number;
  }>({
    chaplist: [],
    chapTotal: 0,
    pageIndex: 1,
  });

  // 进入阅读页
  const goDetail = (cId: number) => {
    if (navigation && cId !== chapId) {
      navigation.navigate('reader-detail', {
        chapId: cId,
        bId,
        conTitle,
        type,
        author,
        chapterCount,
      });
    }
  };

  // 章节列表
  const getChapList = useCallback(
    (idx: number, isMore?: boolean) => {
      if (userInfo?.Token && bId) {
        postChapterList({
          BID: bId,
          IsDrop: false,
          PageIndex: idx,
          PageSize: 10,
          UT: userInfo?.Token,
        })
          .then((res: any) => {
            if (Array.isArray(res?.Data)) {
              setChapList(preCl => ({
                chaplist: isMore ? [...preCl.chaplist, ...res.Data] : res.Data,
                chapTotal: res.Count,
                pageIndex: idx,
              }));
            } else {
              throw new Error('');
            }
          })
          .catch(err => {
            console.log({err});
          });
      }
    },
    [bId, userInfo?.Token],
  );

  // 章节列表加载更多
  const onChapterListMore = useCallback(() => {
    if (chapTotal > chaplist.length) {
      getChapList(pageIndex + 1, true);
    }
  }, [getChapList, pageIndex, chapTotal, chaplist.length]);

  useFocusEffect(
    useCallback(() => {
      getChapList(1);
    }, [getChapList]),
  );

  // 获取章节信息
  const getData = useCallback(
    (ChapterId: number, isMore?: boolean, isBuy?: boolean, cb?: () => void) => {
      if (userInfo?.Token && bId && ChapterId) {
        postChapterInfo({
          ArticleId: bId,
          ChapterId,
          UT: userInfo?.Token,
        })
          .then((res: any) => {
            setData(pred => {
              if (isBuy) {
                return [
                  ...pred.map(it => {
                    if (it.ChapterId === ChapterId) {
                      return res.Data;
                    }
                    return it;
                  }),
                ];
              }
              if (isMore) {
                return [...pred, res.Data];
              }
              return [res.Data];
            });
            if (!isMore) {
              setTitle(res.Data?.Title);
            }
          })
          .catch(() => {})
          .finally(() => {
            if (typeof cb === 'function') {
              cb();
            }
          });
      }
    },
    [userInfo?.Token, bId],
  );

  const getCoins = useCallback(() => {
    if (userInfo?.Token) {
      UserAssets({UT: userInfo?.Token})
        .then((res: any) => {
          setCoin(res?.Data?.Coins);
        })
        .catch(() => {});
    }
  }, [userInfo?.Token]);

  // 购买章节
  const onBuyChapter = useCallback(
    (cId: number) => {
      if (cId) {
        BuyChapter({
          ArticleId: bId,
          ChapterId: cId,
          UT: userInfo?.Token,
        })
          .then(() => {
            getCoins();
            getData(cId, false, true);
            getChapList(1);
          })
          .catch(() => {});
      }
    },
    [bId, userInfo?.Token, getChapList],
  );

  useFocusEffect(getCoins);

  useFocusEffect(
    useCallback(() => {
      getData(chapId);
    }, [chapId, getData]),
  );

  const _randItem = ({item}: {item: DataItem}) => {
    const toVip = () => {
      navigation.navigate('to-pay');
    };

    const toPay = () => {
      if (coin >= item.Points) {
        onBuyChapter(item.ChapterId);
      } else {
        toVip();
      }
    };

    const afterNode =
      !item.FreeFlag && !item.HasPurchase ? (
        <View>
          <ObserverView
            style={{height: dpw12}}
            themeStyle={{backgroundColor: 'color_12'}}
          />
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              paddingHorizontal: dpw12,
              paddingBottom: dpw16,
              paddingTop: dpw12,
            }}>
            <View>
              <ObserverText
                tKey="chapterBookCoin"
                tOptions={{price: item.Points}}
              />
              <ObserverText tKey="useMoneyView" type="desc" />
            </View>
            <TouchableOpacity onPress={toVip}>
              <ObserverText type="primary" tKey="openVip" />
            </TouchableOpacity>
          </View>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              paddingHorizontal: dpw12,
              paddingBottom: dpw16,
            }}>
            <View>
              <ObserverText tKey="autoBuy" />
              <ObserverText tKey="autoBuyDesc" type="desc" />
            </View>
            <AutoPayChapter />
          </View>
          <View
            style={{
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              paddingHorizontal: dpw12,
              paddingBottom: dpw16,
            }}>
            <ObserverText tKey="userCoin" />
            <ObserverText tKey={`${coin}`} type="primary" />
          </View>
          <ObserverButton
            style={{borderRadius: 0}}
            tKey={coin >= item.Points ? 'immediatePayment' : 'noHasMoney'}
            tOptions={coin >= item.Points ? {amont: item.Points} : {}}
            onPress={toPay}
            type="primary"
          />
        </View>
      ) : null;

    return (
      <LoadImgs
        list={item.ImageList}
        afterNode={afterNode}
        cId={item.ChapterId}
      />
    );
  };

  const onLoadMore = () => {
    if (!isScrollUp && Array.isArray(data) && data.length > 0) {
      const lastData = data[data.length - 1];
      if (
        (lastData.FreeFlag || lastData.HasPurchase) &&
        lastData.NextChapter?.ChapterId
      ) {
        getData(lastData.NextChapter.ChapterId, true);
      }
    }
  };

  const goBack = () => {
    if (navigation) {
      if (!userInfo?.Token) {
        navigation.navigate('Login');
      } else {
        navigation.navigate('cartoon-detail', {bId});
      }
    }
  };

  const onScroll = (event: any) => {
    const currentScrollY = event.nativeEvent.contentOffset.y;
    if (isScrollUp && currentScrollY > lastScrollYRef.current) {
      setIsScrollUp(false);
    } else if (!isScrollUp && currentScrollY < lastScrollYRef.current) {
      setIsScrollUp(true);
    }
    lastScrollYRef.current = currentScrollY;
  };

  const onViewableItemsChanged = ({changed}: any) => {
    const change = changed[0];
    if (change?.isViewable) {
      setTitle(change?.item?.Title);
    }
  };

  const isPreId = Array.isArray(data) && data[0]?.PreviousChapter?.ChapterId;
  const isNextId =
    Array.isArray(data) && data[data.length - 1]?.NextChapter?.ChapterId;

  const openDir = () => {
    setVisible(true);
  };

  const goPrePage = () => {
    if (isPreId) {
      getData(isPreId);
    }
  };

  const goNextPage = () => {
    if (isNextId) {
      getData(isNextId);
    }
  };

  const onChangeFocus = () => {
    if (!foucs && userInfo?.Token) {
      Collect({Id: bId, UT: userInfo?.Token})
        .then(() => {
          changeFoucs(true);
          changeToastKey('focusSuccess');
        })
        .catch(() => {});
    }
  };

  const openSet = () => {};

  return (
    <ObserverView style={{flex: 1}}>
      <ScrollHead
        navigation={navigation}
        goBack={goBack}
        isShow={isScrollUp}
        title={title}
      />
      <ScrollFood
        openDir={openDir}
        goPrePage={goPrePage}
        goNextPage={goNextPage}
        onChangeFocus={onChangeFocus}
        openSet={openSet}
        isShow={isScrollUp}
        hasFollow={foucs}
        isPreDis={isPreId}
        isNextDis={isNextId}
      />
      {Array.isArray(data) && data.length > 0 ? (
        <FlatList
          data={data}
          keyExtractor={item => `${item.ChapterId}`}
          renderItem={_randItem}
          onEndReached={onLoadMore}
          onScroll={onScroll}
          onViewableItemsChanged={onViewableItemsChanged}
          onEndReachedThreshold={0.4}
        />
      ) : (
        <Empty />
      )}
      <Modal visible={visible} animationType="slide" transparent>
        <ModalDir
          Author={author}
          ChapterCount={chapterCount}
          Type={type}
          Title={conTitle}
          list={chaplist}
          bId={bId}
          goDetail={goDetail}
          onEndReached={onChapterListMore}
          onClose={() => {
            setVisible(false);
          }}
        />
      </Modal>
    </ObserverView>
  );
};

export default observer(ReaderDetail);
